<template>
    <div class="login-container">
        <div class="login-box">
            <h2>{{ isRegister ? '注册账号' : '登录' }}</h2>
            <el-form :model="formData" :rules="rules" ref="formRef">
                <el-form-item v-if="isRegister" prop="email">
                    <el-input v-model="formData.email" placeholder="请输入邮箱" clearable>
                        <template #prefix>
                            <el-icon>
                                <Message />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input v-model="formData.username" placeholder="请输入用户名" clearable>
                        <template #prefix>
                            <el-icon>
                                <User />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password clearable>
                        <template #prefix>
                            <el-icon>
                                <Lock />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item v-if="isRegister" prop="confirmPassword">
                    <el-input v-model="formData.confirmPassword" type="password" placeholder="请确认密码" show-password
                        clearable>
                        <template #prefix>
                            <el-icon>
                                <Lock />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item v-if="!isRegister" prop="role">
                    <el-radio-group v-model="formData.role">
                        <el-radio label="user">普通用户</el-radio>
                        <el-radio label="admin">管理员</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="submit-btn" @click="handleSubmit">
                        {{ isRegister ? '注册' : '登录' }}
                    </el-button>
                </el-form-item>
                <div class="form-footer">
                    <el-link v-if="!isRegister" type="primary" @click="toggleMode">
                        没有账号？去注册
                    </el-link>
                    <el-link v-if="isRegister" type="info" @click="toggleMode">
                        返回登录
                    </el-link>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import http from '@/utils/request'
import list from '@/utils/url'

const router = useRouter()
const route = useRoute()

const isRegister = ref(false)
const formRef = ref(null)
const formData = ref({
    email: '',
    username: '',
    password: '',
    confirmPassword: '',
    role: 'user'
})

// 监听路由查询参数，处理从主页面跳转过来的注册请求
onMounted(() => {
    if (route.query.mode === 'register') {
        isRegister.value = true
        // 注册模式下，默认角色为普通用户
        formData.value.role = 'user'
    }
})

// 角色选择表单验证规则，仅在登录模式下验证
const roleRule = [
    { required: true, message: '请选择用户角色', trigger: 'change' }
]

const rules = {
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
    ],
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!value || value.length < 6) {
                    callback(new Error('密码长度不能少于6位'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== formData.value.password) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    role: roleRule
}

const handleSubmit = async () => {
    if (!formRef.value) return
    try {
        await formRef.value.validate()

        try {
            if (isRegister.value) {
                formData.value.role = 'user'
                const res = await http.post(list.list_user_api.register, {
                    email: formData.value.email,
                    username: formData.value.username,
                    password: formData.value.password
                })

                if (res.code === 200) {
                    ElMessage.success('注册成功，请登录')
                    isRegister.value = false
                    formData.value = { email: '', username: formData.value.username, password: '', confirmPassword: '', role: 'user' }
                }
            } else {
                const res = await http.post(list.list_user_api.login, {
                    username: formData.value.username,
                    password: formData.value.password,
                    role: formData.value.role
                })

                if (res.code === 200) {

                    ElMessage.success('登录成功')
                    localStorage.setItem('token', res.data.token)
                    localStorage.setItem('username', formData.value.username)
                    localStorage.setItem('role', formData.value.role)
                    router.push(formData.value.role === 'admin' ? '/admin/dashboard' : '/cloud')
                }
            }
        } catch (error) {
            console.error(error)
        }
    } catch (validationError) {
        ElMessage.error(validationError.message || '表单验证失败')
    }
}


const toggleMode = () => {
    isRegister.value = !isRegister.value
    // 切换到注册模式时，重置表单并设置角色为普通用户
    if (isRegister.value) {
        formData.value.role = 'user'
    }
}
</script>

<style scoped>
.login-container {
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: background 0.5s;
}

.login-box {
    width: 400px;
    padding: 2.5rem 2rem 2rem 2rem;
    background: #fff;
    border-radius: 18px;
    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
    position: relative;
    z-index: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.login-box h2 {
    text-align: center;
    color: var(--el-color-primary);
    margin-bottom: 1.5rem;
    font-weight: 600;
    font-size: 1.5rem;
    letter-spacing: 2px;
}

.el-form {
    width: 100%;
}

.el-form-item {
    margin-bottom: 1.2rem;
}

.el-input__wrapper {
    border-radius: 8px !important;
    background: #f7fafd;
}

.el-input__inner {
    font-size: 1rem;
    padding: 0.7rem 1rem;
}

.el-radio-group {
    display: flex;
    justify-content: flex-start;
    width: 100%;
}

.el-radio {
    flex: none;
    text-align: left;
    border-radius: 0;
    background: none;
    margin: 0 1.5rem 0 0;
    padding: 0;
    transition: none;
}

.el-radio.is-checked {
    background: none;
    color: inherit;
}

.submit-btn {
    width: 100%;
    margin-top: 1rem;
    font-size: 1.1rem;
    border-radius: 8px;
    letter-spacing: 2px;
    box-shadow: 0 2px 8px 0 rgba(31, 38, 135, 0.08);
    transition: background 0.2s, box-shadow 0.2s;
}

.submit-btn:hover {
    background: #74ebd5;
    box-shadow: 0 4px 16px 0 rgba(31, 38, 135, 0.14);
}

.form-footer {
    text-align: center;
    margin-top: 1rem;
    font-size: 0.98rem;
}

.el-link {
    font-weight: 500;
    letter-spacing: 1px;
    transition: color 0.2s;
}

.el-link:hover {
    color: #409eff;
}

@media (max-width: 600px) {
    .login-box {
        width: 95vw;
        min-width: 0;
        padding: 1.2rem 0.5rem 1.5rem 0.5rem;
    }

    .login-box h2 {
        font-size: 1.1rem;
    }
}
</style>